<script setup lang="ts">
import { ref, computed, type ComputedRef, nextTick } from 'vue'
import { getCategoryListAPI, getBannerListAPI } from '@/services/category'
import type { CategoryListItem, IBannerListItem } from '@/types/category'
import type { GoodsResult } from '@/types/goods'
import { onLoad, onPageScroll, onReady, onShow } from '@dcloudio/uni-app'
import CategorySkeleton from './components/CategorySkeleton.vue'
import FlyInCart from '@/components/FlyInCart.vue'
import vkDataGoodsSkuPopupCenter from '@/components/vk-data-goods-sku-popup-center.vue'
import wucTab from '@/components/wuc-tab.vue'
import { useStore, useCart, useCategory } from '@/stores'
import type { IcartItem } from '@/types/cart'
import { getStoreCollectStatusAPI } from '@/services/store'
const { addCartData, getCartTotalNum, removeCartData } = useCart()
const { getBuyMethodList, getBuyMethodName, getBuyMethodActiveIndex, setBuyMethodActiveIndex } =
  useCategory()
const { getStoreInfo, changeLocalAddressLatAndLog } = useStore()
onLoad(() => {
  console.log('index', getBuyMethodActiveIndex())
})
const { screenHeight, windowHeight } = uni.getSystemInfoSync()
const initParams = {
  eatType: '0',
  categoryId: null,
  dateOrderBy: null,
  priceOrderBy: null,
}
const categoryParams = ref(initParams as any)

// 获取轮播图数据
const bannerList = ref<IBannerListItem[]>([])
const tabOptionList: any = ref([
  { name: '默认', sort: null, arrow: null },
  { name: '销量', sort: null, arrow: null },
  { name: '新品', sort: null, arrow: null },
  { name: '价格', sort: 'asc', arrow: true },
])
const tabOptionCur = ref(0)
const tabOptionChange = async (index: any) => {
  tabOptionList.value = tabOptionList.value.map((item: any, i: number) => {
    if (i === index) {
      if (index === 0 || index === 1) {
        item.sort = null
        categoryParams.value = {
          ...categoryParams.value,
          dateOrderBy: null,
          priceOrderBy: null,
        }
      }
      // 上架时间排序
      if (index === 2 && i === 2) {
        item.sort = 'desc'
        categoryParams.value = {
          ...categoryParams.value,
          dateOrderBy: item.sort,
          priceOrderBy: null,
        }
      }
      // 价格排序
      if (index === 3 && i === 3) {
        item.sort = item.sort === 'asc' ? 'desc' : 'asc'
        categoryParams.value = {
          ...categoryParams.value,
          dateOrderBy: null,
          priceOrderBy: item.sort,
        }
      }
    } else {
      item.sort = null
    }
    return item
  })
  tabOptionCur.value = index

  await getCategoryListRequest()
}
const cartBasketRect = ref({})
const inCart: any = ref(null)

// 获取分类列表数据
const categoryList = ref<CategoryListItem[]>([])
const primaryActiveIndex = ref(0)

const getCategoryListRequest = async () => {
  const res = await getCategoryListAPI({
    ...categoryParams.value,
    eatType: getBuyMethodActiveIndex(),
  })
  categoryList.value = res.data
}
const getBannerListRequst = async () => {
  const res = await getBannerListAPI({
    platform: 'wechat',
    location: 'category',
    type: 'image',
  })
  bannerList.value = res.data
}

/**
 * 初始化选中索引，
 * 一级分类选中索引为0，
 * 二级分类选中索引为0，及其筛选项
 */
const initActiveIndex = () => {
  tabOptionCur.value = 0
  // setBuyMethodActiveIndex(0)
  primaryActiveIndex.value = 0
  categoryParams.value = { ...categoryParams.value, ...initParams }
}

// 是否数据加载完毕
const isFinish = ref(false)

const goodsInfo = ref({})
// 页面加载
onShow(async () => {
  initActiveIndex()
  await Promise.all([getBannerListRequst(), getCategoryListRequest()])
  isFinish.value = true
  setCartTabBarBadge()
})

// 提取当前二级分类数据
const subCategoryList: ComputedRef<GoodsResult[]> = computed(() => {
  return categoryList.value[primaryActiveIndex.value]?.categoryGoodList || []

  // return (
  //   categoryList.value[primaryActiveIndex.value]?.categoryGoodList.map((item: CategoryGoodItem) => {
  //     return { ...item, num: 0 }
  //   }) || []
  // )
})

const isShowSku = ref(false)

const setCartTabBarBadge = () => {
  const totalNum = getCartTotalNum()
  if (totalNum > 0) {
    uni
      .setTabBarBadge({
        index: 2,
        text: totalNum.toString(),
      })
      .catch((err) => {
        console.error('category:', err)
      })
  } else {
    uni.removeTabBarBadge({
      index: 2,
    })
  }
}

const removeToCart = (good: GoodsResult) => {
  if (good['num'] && good['num'] > 0) {
    good['num'] = good.num - 1
    // 加入购物车
    const skuId: number = good['sku_list'][0]['_id']
    const cartRecord: IcartItem = {
      checked: true,
      id: good._id,
      goods_id: good._id,
      description: good.description,
      specification: '',
      name: good.name,
      image: good.imageUrl,
      price: good.price,
      costPrice: 0,
      num: good['num'],
      isSetmeal: 0,
      setmealPid: null,
      hasSku: 0,
      skuId,
    }
    console.log(cartRecord)
    removeCartData(cartRecord, true)
    setCartTabBarBadge()
  }
}
const eventSpec: any = ref(null)

/**
 * 加入购物车
 */
const addToCart = (good: GoodsResult, e: any) => {
  good['num'] = (good.num || 0) + 1
  inCart.value.addToCart(e, good._id)
  const skuId: number = good['sku_list'][0]['_id']

  // 加入购物车
  const cartRecord: IcartItem = {
    checked: true,
    id: good._id,
    storeId: getStoreInfo()?.storeId,
    goods_id: good._id,
    name: good.name,
    image: good.imageUrl,
    description: good.description,
    specification: '',
    price: good.price,
    costPrice: 0, // goodsInfo.value.cost * setmealCartTotal.value,
    num: good['num'],
    isSetmeal: 0,
    setmealPid: null,
    hasSku: 0,
    skuId,
  }
  // console.log(goodsInfo)
  console.log(cartRecord)
  addCartData(cartRecord, true)
  setCartTabBarBadge()
}

// 页面滚动事件
onPageScroll(() => {
  // 调用是因为 重复使用了点击动画位置 保证不抖动。 不传参调用即清空点击点
  inCart.value?.addToCart()
})

const onOpenSkuPopup = (good: any, e: any) => {
  eventSpec.value = e
  goodsInfo.value = good
  isShowSku.value = true
}

const onSetmealOpenSkuPopup = (good: any, e: any) => {
  uni.navigateTo({
    url: `/pages/goods/setmealGoods?id=${good._id}`,
  })
}

const buyMethodList = ref(getBuyMethodList())

const onCloseSkuPopup = (ev: any) => {
  console.log('onCloseSkuPopup2', ev)
}
const addCart = async (ev: any) => {
  isShowSku.value = false
  let record: any = {}
  const res = categoryList.value[primaryActiveIndex.value]?.categoryGoodList || []
  categoryList.value[primaryActiveIndex.value].categoryGoodList = res.map(
    (item: any, index: number) => {
      if (item._id === ev.goods_id) {
        inCart.value.addToCart(eventSpec.value, ev.goods_id)
        record = { ...item, num: ev.buy_num }
        return { ...item, num: ev.buy_num }
      }
      return item
    },
  )

  // setCartTabBarBadge()
  eventSpec.value = null

  console.log(ev)
  console.log(categoryList.value[primaryActiveIndex.value].categoryGoodList)

  // 加入购物车
  const cartRecord: IcartItem = {
    checked: true,
    storeId: getStoreInfo()?.storeId,
    id: ev._id,
    goods_id: record._id,
    hasSku: record.hasSku,
    name: ev.goods_name,
    image: ev.image,
    description: record.description,
    specification: ev.specification,
    price: ev.price,
    costPrice: ev.cost,
    num: ev.buy_num,
    isSetmeal: 0,
    setmealPid: null,
    skuId: ev._id,
  }
  console.log(cartRecord)
  addCartData(cartRecord, false)
  setCartTabBarBadge()
}

// 页面加载完成事件
onReady(() => {
  let q = uni.createSelectorQuery()
  // 获取购物车位置
  setTimeout(() => {
    q.select('#cart')
      .boundingClientRect((data) => {
        cartBasketRect.value = data
      })
      .exec()
  }, 100)
})

const ishidden = ref(true)
const scrolltoupper = () => {
  ishidden.value = true
}
const onScrolltolower = () => {
  ishidden.value = false
}

const primaryTapHandler = async (item: any, index: number) => {
  primaryActiveIndex.value = index
}

const buyMethodHandler = async (item: any, index: number) => {
  categoryList.value = []
  setBuyMethodActiveIndex(index)
  primaryActiveIndex.value = 0
  // 动态设置
  categoryParams.value = {
    ...categoryParams.value,
    eatType: item.value.toString(),
  }

  await getCategoryListRequest()
}

// 跳转到banner活动页
const bannerNavigatorHandler = (item: IBannerListItem) => {
  uni.navigateTo({
    url: item.linkUrl,
  })
}

const storeNavigatorHandler = () => {
  uni.getLocation({
    type: 'gcj02', // 'wgs84', //
    isHighAccuracy: true,
    geocode: true,
    success: async (res: any) => {
      uni.navigateTo({
        url: `/pagesStore/store/store?latitude=${res.latitude}&longitude=${res.longitude}`,
      })
    },
    fail: (res: any) => {
      console.error(res)
    },
    complete: (res: any) => {},
  })
}
</script>

<template>
  <view class="category-page">
    <!-- 购物车动画 -->
    <FlyInCart ref="inCart" :cartBasketRect="cartBasketRect" />
    <view id="cart"></view>

    <vk-data-goods-sku-popup-center
      ref="skuPopup"
      v-model="isShowSku"
      border-radius="20"
      :z-index="990"
      :localdata="goodsInfo"
      :mode="2"
      :amount-type="0"
      :stepBuyNum="1"
      :minBuyNum="1"
      theme="black-white"
      @close="onCloseSkuPopup"
      @add-cart="addCart"
    ></vk-data-goods-sku-popup-center>

    <scroll-view
      class="category-scroll"
      scroll-y
      :show-scrollbar="false"
      enable-back-to-top
      @scrolltoupper="scrolltoupper"
      @scrolltolower="onScrolltolower"
    >
      <view class="category-page" v-if="isFinish">
        <view class="banner-wrap">
          <swiper
            class="swiper"
            :circular="true"
            :indicator-color="'rgba(255, 255, 255, 0.5)'"
            :indicator-active-color="'rgba(255, 255, 255, 1)'"
            :indicator-dots="true"
            :autoplay="false"
            v-if="bannerList?.length"
          >
            <swiper-item v-for="item in bannerList" :key="item.id">
              <view class="swiper-item uni-bg-red" @tap="bannerNavigatorHandler(item)"
                ><image :src="item.imageUrl" mode="scaleToFill"
              /></view>
            </swiper-item>
          </swiper>
          <view v-else class="no-data"><text>没有数据</text></view>
        </view>

        <view class="address">
          <view class="store" @tap="storeNavigatorHandler">
            <!-- <view class="store" url="/pagesStore/store/store" hover-class="none"> -->
            <text class="icon"></text>
            <view class="con">
              <text class="title">{{ getStoreInfo()?.storeName }}</text>
              <text class="info">{{ getStoreInfo()?.address }}</text>
            </view>
          </view>
          <!-- 就餐方式 -->
          <view class="btn-group">
            <text
              v-for="(item, index) in buyMethodList"
              :key="index"
              class="btn"
              :class="{ active: getBuyMethodActiveIndex() === index }"
              @tap="buyMethodHandler(item, index)"
              >{{ item.name }}</text
            >

            <text class="cur" :style="{ left: getBuyMethodActiveIndex() * 80 + 'rpx' }"></text>
          </view>
        </view>

        <!-- 搜索框 -->
        <view class="search">
          <navigator
            class="input"
            :url="`/pagesMember/search/search?eatType=${getBuyMethodActiveIndex()}`"
            hover-class="none"
          >
            <text class="icon-search">请输入搜索关键字…</text>
          </navigator>
        </view>
        <!-- 分类 -->
        <view class="categories" :style="{ height: windowHeight + 'px' }">
          <scroll-view
            class="primary"
            scroll-y
            :show-scrollbar="false"
            enable-back-to-top
            @scrolltoupper="scrolltoupper"
            @scrolltolower="onScrolltolower"
            v-if="categoryList.length"
          >
            <view
              class="item"
              v-for="(item, index) in categoryList"
              :key="item.id"
              :class="{ active: index === primaryActiveIndex }"
              @tap="primaryTapHandler(item, index)"
            >
              {{ item.name }}
            </view>
          </scroll-view>
          <view v-else class="no-data primary"><text>没有数据</text></view>
          <view class="main">
            <wuc-tab
              tabClass="option-tab"
              :tab-list="tabOptionList"
              :tabCur="tabOptionCur"
              @change="tabOptionChange"
            ></wuc-tab>
            <scroll-view
              class="secondary"
              scroll-y
              :show-scrollbar="false"
              enable-back-to-top
              @scrolltoupper="scrolltoupper"
              @scrolltolower="onScrolltolower"
              v-if="categoryList.length"
            >
              <view class="panel" v-for="item in subCategoryList" :key="item._id">
                <view class="section">
                  <navigator
                    :key="item._id"
                    class="goods"
                    hover-class="none"
                    :url="
                      item.isSetmeal
                        ? `/pages/goods/setmealGoods?id=${item._id}`
                        : `/pages/goods/goods?id=${item._id}`
                    "
                  >
                    <image class="image" :src="item.goods_thumb"></image>
                    <view class="desc">
                      <view class="name ellipsis">{{ item.name }}</view>
                      <view class="con ellipsis">
                        <rich-text :nodes="item.description"></rich-text>
                      </view>
                      <view class="desc-price">
                        <view class="price">
                          <text class="symbol">¥</text>
                          <text class="symbol">{{ item.price }}{{ item.hasSku ? '起' : '' }}</text>
                        </view>
                        <!-- 是否有规格，还是单品 -->
                        <view class="bottom-right" @click.stop v-if="item.isSetmeal">
                          <view
                            class="spec setmeal"
                            @click.stop="onSetmealOpenSkuPopup(item, $event)"
                            >选规格<text class="tag" v-if="item?.num">{{ item.num }}</text></view
                          >
                        </view>
                        <view
                          v-else-if="!item.isSetmeal && !item.hasSku"
                          class="bottom-right"
                          @click.stop
                        >
                          <template v-if="item?.num">
                            <view class="down" @click.stop="removeToCart(item)"></view>
                            <view class="number">
                              {{ item.num }}
                            </view>
                          </template>
                          <view class="up" @click.stop="addToCart(item, $event)"></view>
                        </view>
                        <view class="bottom-right" @click.stop v-else>
                          <view class="spec setmeal" @click.stop="onOpenSkuPopup(item, $event)"
                            >选规格<text class="tag" v-if="item?.num">{{ item.num }}</text></view
                          >
                        </view>
                      </view>
                    </view>
                  </navigator>
                </view>
              </view>
            </scroll-view>
            <view v-else class="no-data secondary"><text>没有数据</text></view>
          </view>
        </view>
      </view>
      <!-- 骨架屏 -->
      <CategorySkeleton v-else />
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
}
#cart {
  position: fixed;
  bottom: 0;
  right: 35%;
  width: 40rpx;
  height: 40rpx;
}
.category-page {
  height: 100%;
  display: flex;
  flex-direction: column;

  .banner-wrap {
    padding: 10rpx $lager-padding;
    box-sizing: border-box;
    width: 100%;
    height: 120 * $rpx_ratio;
    background-color: $background-color;
    .swiper {
      border-radius: $border-lager-radius;
      .swiper-item {
        height: 100%;
      }
    }
  }
  .category-scroll {
    .category-page {
      display: flex;
      flex-direction: column;

      .categories {
        // flex: 1;
        // height: 1055rpx;
        min-height: 400rpx;
        display: flex;
      }

      /* 针对 H5 端 */
      ::-webkit-scrollbar {
        display: none; /* 隐藏滚动条 */
      }
    }
  }

  .search {
    padding: 0 30rpx 20rpx;
    background-color: #fff;
    .input {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 76rpx;
      padding-left: 26rpx;
      color: #8b8b8b;
      font-size: 28rpx;
      border-radius: 38rpx;
      background-color: #f3f4f4;
      .icon-search {
        font-size: $font-size;
        font-weight: $font-regular-weight;
        color: #8b8b8b;
        display: flex;
        align-items: center;
        &::before {
          margin-right: 20rpx;
          margin-left: -10rpx;
          content: '\e840';
          font-family: 'iconfont' !important;
          font-size: $font-medium-size;
          color: #8b8b8b;
        }
      }
    }
  }
  /* 分类 */

  /* 一级分类 */
  .primary {
    overflow: hidden;
    width: 200rpx;
    flex: none;
    background-color: $background-color;
    font-weight: $font-regular-weight;
    .item {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 56 * $rpx_ratio;
      font-size: $font-size;
      color: $font-color;
      position: relative;
      // &::after {
      //   content: '';
      //   position: absolute;
      //   left: 42rpx;
      //   bottom: 0;
      //   width: 100%;
      //   border-top: 1rpx solid #e3e4e7;
      // }
    }
    .active {
      background-color: #fff;
      color: $color;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: $tag-one-width-highlight;
        height: 100%;
        background-color: $color;
      }
    }
  }
  .primary .item:last-child::after,
  .primary .active::after {
    display: none;
  }
  /* 二级分类 */
  .main {
    background-color: green;
    display: flex;
    flex-direction: column;
    .option-tab {
      .wuc-contanier-tab {
        .wuc-tab-item {
          // background-color: #f9fafb;
          font-size: $font-size;
          color: #4b5563;

          height: 62rpx;
          line-height: 62rpx;
          // border-radius: 31rpx;

          &.cur {
            background-color: $color;
            font-size: $font-size;
            color: #fff;
            .price-icon {
              &::after {
                color: #fff;
              }
            }
          }

          margin: 20rpx 2rpx;
        }
      }
    }

    .secondary {
      background-color: #fff;
      flex: 1;
      height: 100%;

      .panel {
        padding: 0 20rpx $one-padding 20rpx;
        flex: 1;
        .title {
          height: 60rpx;
          line-height: 60rpx;
          color: #333;
          font-size: 28rpx;
          border-bottom: 1rpx solid #f7f7f8;
          .more {
            float: right;
            padding-left: 20rpx;
            font-size: 24rpx;
            color: #999;
          }
        }
        .more {
          &::after {
            font-family: 'erabbit' !important;
            content: '\e6c2';
          }
        }
        .section {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          // padding: 20rpx 0;
          .goods {
            width: 100%;
            margin-bottom: 32rpx;
            display: flex;
            border: 1px solid $border-color;
            border-radius: $border-medium-radius;
            padding: $small-padding;
            image {
              width: 160rpx;
              height: 160rpx;
              border-radius: $border-small-radius;
            }
            .desc {
              flex: 1;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              padding-left: 32rpx;
              .name {
                font-size: $font-medium-size;
                color: $good-font-title-color;
                font-weight: $font-medium-weight;
              }
              .con {
                font-size: $font-size;
                color: $good-font-con-color;
                font-weight: $font-regular-weight;
              }
              .desc-price {
                display: flex;
                align-items: center;
                .price {
                  font-size: $font-medium-size;
                  font-weight: $font-medium-weight;
                  color: $price-font-color;
                  .symbol {
                  }
                }

                .bottom-right {
                  margin-left: auto;
                  display: flex;
                  align-items: center;
                  margin-top: auto;
                  font-size: 18rpx;
                  .spec {
                    font-size: $font-size;
                    color: $color;
                    box-sizing: border-box;
                    height: 48rpx;
                    line-height: 1.66;
                    border: 1px solid $color;
                    padding: 0 20rpx;
                    border-radius: 24rpx;
                    position: relative;
                    &.setmeal {
                      background-color: $color;
                      color: #fff;
                    }
                    .tag {
                      position: absolute;
                      right: -26rpx;
                      top: -29rpx;
                      max-width: 60rpx;
                      max-height: 30rpx;
                      min-width: 30rpx;
                      min-height: 30rpx;
                      background-color: #fa5151;
                      padding: 8rpx;
                      border-radius: 50%;
                      color: #fff;
                      text-align: center;
                      line-height: 30rpx;
                      border: 1px solid #fff4ed;
                    }
                  }
                  .down {
                    &::before {
                      content: '\e619';
                      font-family: 'iconfont' !important;
                      font-size: 46rpx;
                      color: $color;
                    }
                  }
                  .up {
                    &::before {
                      content: '\e647';
                      font-family: 'iconfont' !important;
                      color: $color;
                      font-size: 46rpx;
                    }
                  }
                  .number {
                    margin: 0 16rpx;
                    font-size: $font-medium-size;
                    font-weight: $font-medium-weight;
                    color: $good-font-title-color;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .address {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 0 32rpx;
    margin-bottom: 32rpx;
    padding-top: 32rpx;
    .store {
      flex: 1;
      display: flex;
      flex-direction: row;
      align-items: center;
      .icon {
        margin-right: 20rpx;
        &::before {
          content: '\e83d';
          font-family: 'iconfont' !important;
          color: $color;
          font-size: 40rpx;
        }
      }
      .con {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .title {
          font-size: $font-size;
          color: $good-font-title-color;
          font-weight: $font-medium-weight;
        }
        .info {
          font-size: $font-size;
          color: $good-font-con-color;
          font-weight: $font-weight;
          @include lines-ellipsis-style(1);
        }
      }
    }

    .btn-group {
      display: flex;
      flex-direction: row;
      align-items: center;
      height: 48rpx;
      line-height: 48rpx;
      border-radius: 24rpx;
      overflow: hidden;
      &::after {
        content: '';
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border: 1px solid $border-color;
        background-color: $background-color;
        box-sizing: border-box;
        padding: 1rpx;
      }
      position: relative;
      box-sizing: border-box;
      $width: 80rpx;
      text {
        font-size: 28rpx;
        width: $width;
        text-align: center;
        height: auto;
        color: $good-font-con-color;
      }
      .active {
        color: #fff;
      }
      .cur {
        position: absolute;
        left: 0;
        top: -1px;
        background-color: $color;
        border-radius: 24rpx;
        border: 1px solid #fff;
        width: $width;
        height: 100%;
        z-index: -1;
        color: #fff;
        // transition: all 0.2s;
      }
    }
  }
}
</style>
